#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql.cursors

# 用户名
myUser = "root"
# 密码
myPwd = "MyNewPass4!"
# 数据库前缀
dbt = "report{}"

# 执行的SQL字符串
sql = """CREATE TABLE `test_c` (
`id` varchar(40) NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""


# 连接并执行
def create_table(h, p, mdb):
    # 连接数据库
    connect = pymysql.Connect(
        host=h,
        port=p,
        user=myUser,
        passwd=myPwd,
        db=mdb,
        charset='utf8'
    )
    # 获取游标
    cursor = connect.cursor()
    cursor.execute(sql)
    # 关闭连接
    cursor.close()
    connect.close()


# test 数据库连接字符串属性
dbs = {
    "172.27.1.126": {
        "3306": {
            0: "1,2",
            1: "3,40"
        }
    }
}

# yun-pro 数据库连接字符串属性
# dbs = {
#     "db101": {
#         "4101": {
#             0: "0,1,2"
#         },
#         "5101": {
#             1: "201,300"
#         }
#     },
#     "db201": {
#         "4201": {
#             0: "25,26",
#             1: "3,23"
#         },
#         "6201": {
#             1: "27,39",
#             2: "42,76"
#         }
#     },
#     "db301": {
#         "6301": {
#             1: "79,120"
#         }
#     },
#     "db401": {
#         "5401": {
#             0: "77,78,153,154",
#             1: "121,150",
#             2: "156,200"
#         }
#     },
#     "db501": {
#         "4501": {
#             0: "151,152,155"
#         },
#         "5501": {
#             0: "24"
#         },
#         "6501": {
#             0: "40,41"
#         }
#     },
# }


# 执行
for i in dbs:
    host = i
    i = dbs[i]
    for j in i:
        port = int(j)
        j = i[j]
        print(host)
        print(port)
        for x in j:
            xs = x
            x = j[x]
            if xs == 0:
                for y in x.split(","):
                    db = dbt.format(y)
                    create_table(host, port, db)
                    print(db)
            else:
                nu = x.split(",")
                nux = int(nu[1]) - int(nu[0])
                z = 0
                while z <= nux:
                    t = z + int(nu[0])
                    db = dbt.format(t)
                    create_table(host, port, db)
                    z += 1
                    print(db)
